<template>
    <div>
        <div>
            <el-divider content-position="left">您具有一定的操作权限</el-divider>
        </div>

        <div>
            <el-divider>
                <span id="spanlittlepart">查询</span>
            </el-divider>
        </div>

        <!-- 查询 -->
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="植株名" style="width: 150px;">
                <el-input v-model="checkformInline.cropname" placeholder="cropname"></el-input>
            </el-form-item>
            <el-form-item style="width: 200px;">
                <el-button @click="search" type="primary" plain style="width: 200px;">查询</el-button>
            </el-form-item>
        </el-form>

        <el-divider>
            <el-icon><star-filled /></el-icon>
        </el-divider>

        <el-button type="primary" plain :onclick="onAddItem" class="addbtn">
            <el-icon>
                <Edit />
            </el-icon>
            <span> 创建新的轮播图</span>
        </el-button>

        <!-- Form新建 -->
        <el-dialog v-model="dialogaddFormVisible" title="新建项">
            <el-form :model="addform">
                <el-form-item label="植株名" :label-width="formLabelWidth">
                    <el-select v-model="addform.cropname" placeholder="请选择植株">
                        <div v-for="item in cropOptions" :key="item.label">
                            <el-option :label="item.label" :value="item.value" />
                        </div>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-upload v-model:file-list="plantswiperfileList" class="upload-demo" action="#"
                :on-preview="handleRemoveswiperimg" :auto-upload="false" :before-upload="handleChangeswiperimg"
                :on-remove="handlePreviewswiperimg" list-type="picture">
                <el-button type="primary">点击上传轮播图图片</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传图片文件，如上传多张图片：图片总大小应小于20MB，如超过20MB请压缩图片或进行多次上传
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closemodal">取消</el-button>
                    <el-button type="primary" @click="onaddSaveInfo">
                        提交
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 展示表格 -->
        <el-table :data="tableData" style="width: 100%" :highlight-current-row="true" :span-method="objectSpanMethod">
            <el-table-column prop="cropname" label="植株名" width="" />
            <el-table-column label="轮播图" width="">
                <template #default="scope">
                    <el-button @click="showDesc(scope.$index, scope.row)" style="margin-left: -10px;">点击查看商品详情图片</el-button>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作1" width="200">
                <template #default="scope">
                    <el-button link type="primary" size="small"
                        @click.prevent="handleEdit(scope.$index, scope.row)">编辑</el-button>
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作2" width="200">
                <template #default="scope">
                    <el-button link type="primary" size="small"
                        @click.prevent="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 查看商品详情 -->
        <el-dialog v-model="dialogdescFormVisible" title="轮播图图片">
            <el-form :model="tableData[desci].swiperimg">
                <div v-for="(item, i) in tableData[(this.page - 1) * this.size + desci].swiperimg" :key="i">
                    <el-image
                        style=" padding-left: -30px;margin-left: -30px;margin-right: 40px;margin-bottom: 10px; overflow: visible; display: block; "
                        :src="item"
                        :preview-src-list="tableData[(this.page - 1) * this.size + desci].swiperimg"
                        :preview-teleported="true" :initial-index="i" />
                </div>
            </el-form>
        </el-dialog>

        <el-pagination background layout="prev, pager, next" :current-page="page" @update:current-page="handleCurrentChange"
            :total="total" :page-size="size" style="bottom: 0; text-align: center;margin-left: 35%;margin-top: 5px;" />

        <!-- Form -->
        <el-dialog v-model="dialogFormVisible" title="编辑">
            <el-form :model="form">
                <el-form-item label="植株名" :label-width="formLabelWidth">
                    <el-select v-model="form.cropname" placeholder="请选择植株">
                        <div v-for="item in cropOptions" :key="item.label">
                            <el-option :label="item.label" :value="item.value" />
                        </div>
                    </el-select>
                </el-form-item>
            </el-form>
            <el-upload v-model:file-list="editfileList" class="upload-demo" action="#" :on-preview="handlePreview"
                :auto-upload="false" :before-upload="handleChange" :on-remove="handleRemove" list-type="picture">
                <el-button type="primary">点击进行轮播图上传</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        只能上传图片文件，如上传多张图片：图片总大小应小于20MB，如超过1MB请压缩图片或进行多次上传
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="onSaveInfo">
                        提交
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import {
    Guide,
    PictureFilled,
    User,
    HomeFilled,
    ChatLineSquare,
    Apple,
    Document,
    List,
    Tools,
    ShoppingCart,
    CollectionTag,
    Finished,
    InfoFilled,
    Cherry,
    Goods,
    Sell,
    ShoppingCartFull,
    Van,
    Sunrise,
    StarFilled,
    EditPen,
    Edit,
    Promotion,
    Grape,
    Pear,
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
const formLabelWidth = '140px';
const filterHandler = (
    value,
    row,
    column
) => {
    const property = column['property']
    return row[property] === value
}
</script>
<script>

export default {
    data() {
        return {
            baseURL: 'http://localhost:8080',
            cropChosen: 0,
            cropOptions: [],
            formInline: {
                id: '',
                cropsid: '',
                cropname: '',
                swiperimg: '',
                cropall: '',
            },
            checkformInline: {
                id: '',
                cropsid: '',
                cropname: '',
                swiperimg: '',
                cropall: '',
            },
            dialogFormVisible: false,
            dialogaddFormVisible: false,
            showSearch: false,
            tableData: [],
            tableDataStore: [],
            tableimgList: [],
            tableimg: '',
            growtime: {
                id: '',
                cropsid: '',
                cropname: '',
                swiperimg: '',
                cropall: '',
            },
            basedata: '',
            form: {
                id: '',
                cropsid: '',
                cropname: '',
                swiperimg: '',
                cropall: '',
            },
            addform: {
                id: '',
                cropsid: '',
                cropname: '',
                swiperimg: '',
                cropall: '',
            },
            searchForm: [],
            filetype: [
                "jpg",
                "jpeg",
                "png",
            ],
            page: 1, // 当前页码
            total: 0, // 总条数
            size: 8, // 每页的数据条数
            reallyTable: [],
            selData: [],
            editfileList: [],   //编辑modal种商品描述图片的列表
            growimgfileList: [],
            plantswiperfileList: [],
            plantswiperfileArray: [],
            fileArray: [],
            fileList: [],
            desci: 0,
            dialogdescFormVisible: false,
            formdesc: [],
            tableimgListList: [[]],
        }
    },
    methods: {
        showDesc(index, row) {
            this.desci = index
            console.log(this.tableData[this.desci].swiperimg);
            this.dialogdescFormVisible = true
        },
        init() {
            axios({
                method: 'post',
                url: 'http://localhost:8080/plantswiper/getplantswiperbackend',
                withCredentials: true,
            }).then(res => {
                this.tableData = res.data.data;
                this.tableDataStore = res.data.data;
                console.log(res.data.data);
                this.tableData = res.data.data.slice(
                    (this.page - 1) * this.size,
                    this.page * this.size
                );
                this.total = res.data.data.length;
                this.selData = res.data.data;

                for (var i = 0; i < res.data.data.length; i++) {
                    if (res.data.data[i].swiperimg != null) {
                        if (Array.isArray(res.data.data[i].swiperimg)) {
                            for (let j = 0; j < res.data.data[i].swiperimg.length; j++) {
                                res.data.data[i].swiperimg[j] = this.baseURL + res.data.data[i].swiperimg[j]
                            }
                            this.tableimgListList[i] = res.data.data[i].swiperimg
                            this.tableimg = this.baseURL + this.tableimgListList[0][0];
                            //console.log(this.tableimgListList);

                            this.formdesc[i] = res.data.data[i].swiperimg
                        } else {
                            this.tableimgList.push(res.data.data[i].swiperimg);
                            console.log(this.tableimgList);
                            this.tableimg = this.baseURL + this.tableimgList[0];

                            this.formdesc[i].push(res.data.data[i].swiperimg)
                        }
                    } else {
                        console.log('else')
                    }
                    this.cropOptions.push({ value: res.data.data[i].cropall, label: res.data.data[i].cropall });
                }
                this.handleArr(this.cropOptions);
                this.cropOptions.pop();
                console.log(this.cropOptions);
            })
        },
        search() {
            let arr = []
            console.log(this.tableDataStore.length)
            for (let i = 0; i < this.tableDataStore.length; i++) {
                if (String(this.tableDataStore[i].cropname).includes(this.checkformInline.cropname)) {
                    arr.push(this.tableDataStore[i])
                }
            }
            console.log(arr);
            this.size = 8;
            this.tableData = arr.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            this.selData = arr;
            this.total = arr.length;
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 8) {
                if (rowIndex % 4 === 0) {
                    return {
                        rowspan: 4,
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },
        //删除表格行
        handleDelete(index, row) {
            console.log(index, row);
            console.log(row.id);//可以获取到
            console.log(this.tableData[index]);
            ElMessageBox.confirm(
                '确认删除本项吗？删除后无法找回:-0',
                'Warning',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    axios({
                        method: 'post',
                        url: 'http://localhost:8080/plantswiper/delswiperimgbackend',
                        withCredentials: true,
                        data: {
                            cropsid: row.cropsid,
                            swiperimg: row.swiperimg,
                        },
                    }).then(res => {
                        this.tableData = res.data.data;
                        this.tableDataStore = res.data.data;
                        console.log(res.data.data);
                        this.tableData = res.data.data.slice(
                            (this.page - 1) * this.size,
                            this.page * this.size
                        );
                        this.total = res.data.data.length;
                        this.selData = res.data.data;

                        for (var i = 0; i < res.data.data.length; i++) {
                            if (res.data.data[i].swiperimg != null) {
                                if (Array.isArray(res.data.data[i].swiperimg)) {
                                    for (let j = 0; j < res.data.data[i].swiperimg.length; j++) {
                                        res.data.data[i].swiperimg[j] = this.baseURL + res.data.data[i].swiperimg[j]
                                    }
                                    this.tableimgListList[i] = res.data.data[i].swiperimg
                                    this.tableimg = this.baseURL + this.tableimgListList[0][0];
                                    //console.log(this.tableimgListList);

                                    this.formdesc[i] = res.data.data[i].swiperimg
                                } else {
                                    this.tableimgList.push(res.data.data[i].swiperimg);
                                    console.log(this.tableimgList);
                                    this.tableimg = this.baseURL + this.tableimgList[0];

                                    this.formdesc[i].push(res.data.data[i].swiperimg)
                                }
                            } else {
                                console.log('else')
                            }
                            this.cropOptions.push({ value: res.data.data[i].cropall, label: res.data.data[i].cropall });
                        }
                        this.handleArr(this.cropOptions);
                        this.cropOptions.pop();
                        console.log(this.cropOptions);
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消删除操作',
                    })
                })
        },
        filterArr(arr1, arr2) {
            var uid1 = []
            var uid2 = []
            for (var i in arr1) {
                uid1.push(arr1[i])
            }
            for (var j in arr2) {
                uid2.push(arr2[j])
            }
            const arr = [...uid1, ...uid2];
            console.log(arr);
            const newArr = arr.filter(item => {
                return !(uid2.includes(item));
            });
            return newArr;
        },
        handleRemove(file, fileList) {
            this.fileList = fileList
        },
        handlePreview(file) {
            console.log(file);
        },
        handleChange(file, fileList) {
            let isRightSize = file.size / 1024 / 1024 < 20
            if (!isRightSize) {
                this.$message.error('文件大小超过 20MB')
            }
            let fileName = file.name;
            let pos = fileName.lastIndexOf(".");
            let lastName = fileName.substring(pos, fileName.length);
            let isAccept = true;
            if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".jpeg") {
                this.$message.error("文件必须为.jpg,.png,.jpeg类型");
                isAccept = false;
                // 清空文件列表
                const newFileList = this.fileList.slice();
                newFileList.splice(0, 1);
                this.fileList = newFileList;
            }
        },
        handleRemoveswiperimg(file, fileList) {
            this.plantswiperfileList = fileList
        },
        handlePreviewswiperimg(file) {
            console.log(file);
        },
        handleChangeswiperimg(file, fileList) {
            let isRightSize = file.size / 1024 / 1024 < 20
            if (!isRightSize) {
                this.$message.error('文件大小超过 20MB')
            }
            let fileName = file.name;
            let pos = fileName.lastIndexOf(".");
            let lastName = fileName.substring(pos, fileName.length);
            let isAccept = true;
            if (lastName.toLowerCase() !== ".jpg" && lastName.toLowerCase() !== ".png" && lastName.toLowerCase() !== ".jpeg") {
                this.$message.error("文件必须为.jpg,.png,.jpeg类型");
                isAccept = false;
                // 清空文件列表
                const newFileList = this.plantswiperfileList.slice();
                newFileList.splice(0, 1);
                this.plantswiperfileList = newFileList;
            }
        },
        //编辑表格行
        handleEdit(index, row) {
            console.log(index, row);
            let dif = this.filterArr([1, 2, 3], [2, 3, 4])
            console.log(dif);
            for (let i = 0; i < row.swiperimg.length; i++) {
                this.editfileList.push({ name: '轮播图' + i, url: row.swiperimg[i] })
            }
            this.dialogFormVisible = true;
            axios({
                method: 'post',
                url: 'http://localhost:8080/plantswiper/getsingleplantswiperbackend',
                withCredentials: true,
                data: {
                    id: row.id
                },
            }).then(res => {
                this.form = row;
            })
        },
        async onSaveInfo() {
            if (this.form.cropname != '') {
                const fileArray = this.editfileList;
                console.log(this.editfileList);
                this.fileArray = fileArray
                console.log(fileArray);
                for (let i = fileArray.length - 1; i >= 0; i--) {
                    let lastName = this.getLastName(fileArray, i)
                    await this.getBase64(fileArray[i].url).then(res => {
                        this.fileArray[i].url = res
                        this.fileArray[i].name = new Date().getTime() + Math.floor(Math.random() * (0 - 1000)) + 1000 + '.' + lastName
                    })
                }

                axios({
                    method: 'post',
                    url: 'http://localhost:8080/plantswiper/modifyplantswiperimgbackend',
                    withCredentials: true,
                    data: {
                        id: this.form.id,
                        cropname: this.form.cropname,
                        swiperimg: this.fileArray,
                    },
                }).then(res => {
                    this.tableData = res.data.data;
                    this.tableDataStore = res.data.data;
                    console.log(res.data.data);
                    this.tableData = res.data.data.slice(
                        (this.page - 1) * this.size,
                        this.page * this.size
                    );
                    this.total = res.data.data.length;
                    this.selData = res.data.data;

                    for (var i = 0; i < res.data.data.length; i++) {
                        if (res.data.data[i].swiperimg != null) {
                            if (Array.isArray(res.data.data[i].swiperimg)) {
                                for (let j = 0; j < res.data.data[i].swiperimg.length; j++) {
                                    res.data.data[i].swiperimg[j] = this.baseURL + res.data.data[i].swiperimg[j]
                                }
                                this.tableimgListList[i] = res.data.data[i].swiperimg
                                this.tableimg = this.baseURL + this.tableimgListList[0][0];
                                //console.log(this.tableimgListList);

                                this.formdesc[i] = res.data.data[i].swiperimg
                            } else {
                                this.tableimgList.push(res.data.data[i].swiperimg);
                                console.log(this.tableimgList);
                                this.tableimg = this.baseURL + this.tableimgList[0];

                                this.formdesc[i].push(res.data.data[i].swiperimg)
                            }
                        } else {
                            console.log('else')
                        }
                        this.cropOptions.push({ value: res.data.data[i].cropall, label: res.data.data[i].cropall });
                    }
                    this.handleArr(this.cropOptions);
                    this.cropOptions.pop();
                    console.log(this.cropOptions);
                })
                this.dialogFormVisible = false;
            } else {
                ElMessage.error('存在未输入项')
            }
        },
        async handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.page = val
            this.tableData = this.selData.slice(
                (this.page - 1) * this.size,
                this.page * this.size
            );
            // this.currentPage = val;
            const data = { 'page': val }
            // await this.onload(data)
        },
        //增添项
        onAddItem() {
            this.dialogaddFormVisible = true;
        },
        getLastName(fileArray, i) {
            let pos = fileArray[i].name.lastIndexOf(".");
            let lastName = fileArray[i].name.substring(pos + 1, fileArray[i].name.length);
            console.log(lastName)
            return lastName
        },
        getBase64(imgUrl) {
            return new Promise((resolve, reject) => {
                if (!imgUrl) {
                    reject('请传入imgUrl内容')
                }
                window.URL = window.URL || window.webkitURL
                var xhr = new XMLHttpRequest()
                xhr.open('get', imgUrl, true)
                xhr.responseType = 'blob'
                xhr.onload = function () {
                    if (this.status == 200) {
                        // 得到一个blob对象
                        var blob = this.response
                        const oFileReader = new FileReader()
                        oFileReader.onloadend = function (e) {
                            const base64 = e.target.result
                            resolve(base64 || '')
                        }
                        oFileReader.readAsDataURL(blob)
                    }
                }
                xhr.send()
            })
        },
        closemodal() {
            this.dialogaddFormVisible = false;
            this.fileList = [];
            this.plantswiperfileList = [];
            this.addform = [];
        },
        async onaddSaveInfo() {
            if (this.addform.cropname != '') {
                console.log('submit!')
                const plantswiperfileArray = this.plantswiperfileList;
                this.plantswiperfileArray = plantswiperfileArray;

                for (let i = plantswiperfileArray.length - 1; i >= 0; i--) {
                    let lastName = this.getLastName(plantswiperfileArray, i)
                    await this.getBase64(plantswiperfileArray[i].url).then(res => {
                        this.plantswiperfileArray[i].url = res
                        this.plantswiperfileArray[i].name = new Date().getTime() + Math.floor(Math.random() * (0 - 1000)) + 1000 + '.' + lastName
                    })
                }

                axios({
                    method: 'post',
                    url: 'http://localhost:8080/plantswiper/addplantswiperbackend',
                    withCredentials: true,
                    data: {
                        cropname: this.addform.cropname,
                        swiperimg: this.plantswiperfileArray,
                    },
                }).then(res => {
                    this.tableData = res.data.data;
                    this.tableDataStore = res.data.data;
                    console.log(res.data.data);
                    this.tableData = res.data.data.slice(
                        (this.page - 1) * this.size,
                        this.page * this.size
                    );
                    this.total = res.data.data.length;
                    this.selData = res.data.data;

                    for (var i = 0; i < res.data.data.length; i++) {
                        if (res.data.data[i].swiperimg != null) {
                            if (Array.isArray(res.data.data[i].swiperimg)) {
                                for (let j = 0; j < res.data.data[i].swiperimg.length; j++) {
                                    res.data.data[i].swiperimg[j] = this.baseURL + res.data.data[i].swiperimg[j]
                                }
                                this.tableimgListList[i] = res.data.data[i].swiperimg
                                this.tableimg = this.baseURL + this.tableimgListList[0][0];
                                //console.log(this.tableimgListList);

                                this.formdesc[i] = res.data.data[i].swiperimg
                            } else {
                                this.tableimgList.push(res.data.data[i].swiperimg);
                                console.log(this.tableimgList);
                                this.tableimg = this.baseURL + this.tableimgList[0];

                                this.formdesc[i].push(res.data.data[i].swiperimg)
                            }
                        } else {
                            console.log('else')
                        }
                        this.cropOptions.push({ value: res.data.data[i].cropall, label: res.data.data[i].cropall });
                    }
                    this.handleArr(this.cropOptions);
                    this.cropOptions.pop();
                    console.log(this.cropOptions);
                })
                this.dialogaddFormVisible = false;
            } else {
                ElMessage.error('存在未输入项')
            }
        },
        handleArr(arr) {
            for (let i = 0; i < arr.length; i++) {
                for (let y = i + 1; y < arr.length; y++) {
                    if (arr[i].value === arr[y].value) {
                        arr.splice(y, 1);
                        y--;  //对应上文的splice删除元素的注意事项
                    }
                }
            }
            return arr
        },
    },
    mounted() {
        //页面加载完成后，将数据库内的内容赋给定义的data变量
        this.init()
    }
}
</script>
<style scoped>
#sidepart {
    width: 100%;
    position: absolute;
    top: 5px;
    font-family: '华文中宋';
}

#mainpart {
    width: 100%;
    position: absolute;
    top: 20px;
    /* left: 260px; */
    font-family: '华文中宋';
}

/* dialog */
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

#spanpart {
    font-size: 30px;
    font-family: '华文中宋';
}

#spanlittlepart {
    font-size: 15px;
    color: cadetblue;
    font-family: '华文中宋';
}

.spaninput {
    margin-right: 10px;
    margin-top: 10px;
}

.addbtn {
    width: 80%;
    margin-bottom: 20px;
    font-family: '华文中宋';
    position: relative;
    left: -50px;
}

.previewTitlePic {
    width: 40%;
    margin-bottom: 10px;
}
</style>